package com.ebelter.btcomlib.models.bluetooth.products.scale;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Message;
import android.text.TextUtils;
import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.models.bluetooth.bean.SendMessage;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.BytesUtils;
import com.ebelter.btcomlib.utils.ThreadManager;
import com.ebelter.btcomlib.utils.log.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * 倍泰本公司自己的体脂秤的OTA升级  固件是王雪晶负责 有什么问题可以找他
 */

public class EbelterScaleOtaUpdate extends BaseHandle{


    private static final String TAG = "EbelterScaleOtaUpdate";

    private Context mContext;

    private int updateModel;//0是Asset模式 1是path模式
    private String updateNameOrPath = "a12864.hex";


    public void setUpdateModelAndNameOrPath(int updateModel,String updateNameOrPath) {
        this.updateModel = updateModel;
        this.updateNameOrPath = updateNameOrPath;
    }

    private byte[] ota_ByteLists;
    public static boolean isUpdateing_Flag;//是否正在更新的标志

    private SendMessage otaUpdateRequestSendMsg;//请求ota升级指令


    public List<SendMessage> ota_MsgLists;

    public int otaPosition;

    public EbelterScaleOtaUpdate(Context context) {
        super(context);
        this.mContext=context;
    }

    public void start(){

//        if (isUpdateing_Flag){
//            LogUtils.i(TAG,"---EbelterScaleOtaUpdate--已经是升级状态 无需重新开始 请结束后再 start ");
//            return;
//        }

        isUpdateing_Flag=true;

        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {

                //第一步 初始化
                initOtaBytes();

                //初始化ota升级指令
                otaUpdateRequestSendMsg=new SendMessage();
                otaUpdateRequestSendMsg.desc="请求ota升级指令";
               // byte[] sizeBytes = BytesUtils.getHLByte(ota_ByteLists.length);
                int pSize=ota_ByteLists.length/8;
                int m=ota_ByteLists.length%8;

                if (m!=0){
                    pSize+=1;
                }
                byte[] sizeBytes = BytesUtils.getHLint(pSize);
                int cs= getCS(ota_ByteLists);
                byte[] otaRequest = new byte[]{(byte) 0xab,0x04, (byte) 0x9d,sizeBytes[1],sizeBytes[0], (byte) cs};
                otaUpdateRequestSendMsg.datas = otaRequest;
                otaUpdateRequestSendMsg.isNeedEncrypt=false;

                sendLog2("--------------------\n");
                sendLog2("-----ota--ota_ByteLists.length = "+ota_ByteLists.length+"升级的包的总数="+pSize+"---校验码CS = " + cs);
                LogUtils.i(TAG,"-----ota--ota_ByteLists.length = "+ota_ByteLists.length+"升级的包的总数="+pSize+"---校验码CS = " + cs);
                sendLog2("---pSize="+pSize+"---发送的数据包是="+BytesUtils.getIntFrom2Byte(sizeBytes[0],sizeBytes[1])+"--sizeBytes="+BytesUtils.bytes2HexStr(sizeBytes));
                LogUtils.i(TAG,"---pSize="+pSize+"---发送的数据包是="+BytesUtils.getIntFrom2Byte(sizeBytes[0],sizeBytes[1])+"--sizeBytes="+BytesUtils.bytes2HexStr(sizeBytes));



                sendEmptyMessage(what_init_bytes_finish);
            }
        });


    }







    private void initOtaBytes() {


        if (TextUtils.isEmpty(updateNameOrPath)){
            throw new RuntimeException("updateNameOrPath不能为空 请先设置" );
        }


        byte[] ota_ByteLists2 = new byte[25000];
        int readindex = 0;

        if (updateModel==0){
            AssetManager assetManager = CommonLib.APPContext.getResources().getAssets();
            InputStream input = null;
            try {
                input = assetManager.open(updateNameOrPath);

                long startTime = System.currentTimeMillis();//复制开始时间
                byte[] tempBytes = new byte[256];
                int readLen;

                while ((readLen=input.read(tempBytes)) != -1) {
                    System.arraycopy(tempBytes,0,ota_ByteLists2,readindex,readLen);
                    readindex=readindex+readLen;
                }
                long endTime = System.currentTimeMillis();//复制结束时间
                LogUtils.i(TAG,"--------------复制总用时time = "+(endTime-startTime));


            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            ota_ByteLists=new byte[readindex];
            System.arraycopy(ota_ByteLists2,0,ota_ByteLists,0,readindex);
            //LogUtils.i(TAG,"---------------------------------------------------");


           // ota_ByteLists=new byte[]{1,2,3,4,5,6,7,8,9,10, (byte) 255,2};

            //12升级的包的总数=2---校验码CS = 52


        }else if (updateModel==1){

        }else {
            throw new RuntimeException("updateModel 不是指定的数据 updateModel = "+updateModel);
        }


    }


    private int getCS(byte[] bytes){


        LogUtils.i(TAG,"原bytes="+BytesUtils.bytes2HexStr(bytes));
        int mod=bytes.length%8;

        if (mod!=0){
            int chazhi = 8-mod;
            byte[] temp=new byte[bytes.length+chazhi];
            byte[] temp2 = new byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
            System.arraycopy(bytes,0,temp,0,bytes.length);
            System.arraycopy(temp2,0,temp,bytes.length,chazhi);
            bytes=temp;

            LogUtils.i(TAG,"处理过后的bytes="+BytesUtils.bytes2HexStr(bytes));
        }


        int cs=0;
        for (byte i:bytes){
            cs+=i;
        }
        cs=cs%256;
        return cs;

        //b9 85

    }




    private static final int what_init_bytes_finish = 6;
    private static final int what_init_MsgLists_finish =7;
    private static final int what_sendOtaPosition =8;
    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);

        if (msg.what == what_init_bytes_finish){//第一步 初始化完成
            LogUtils.i(TAG,"--EbelterScaleOtaUpdate--第一步 初始化完成");
            sendLog2("--EbelterScaleOtaUpdate--第一步 初始化完成");
            //第二步 下发升级指令给秤
            sendLog2("--EbelterScaleOtaUpdate--请求ota升级指令"+BytesUtils.bytes2HexStr(otaUpdateRequestSendMsg.datas));



            if (mIOTA!=null)mIOTA.sendMsg2Scale(otaUpdateRequestSendMsg,"请求ota升级指令");
        }else if (msg.what == what_init_MsgLists_finish){
            LogUtils.i(TAG,"--EbelterScaleOtaUpdate--ota集合升级包已经生成");

            sendLog2("--EbelterScaleOtaUpdate--ota集合升级包已经生成");
            otaPosition=0;
            if (mIOTA!=null)mIOTA.sendMsgs2Scale(null,"");

        }

    }





    public void sendOtaList2Scale(int p){
        if (ota_MsgLists!=null&&ota_MsgLists.size()>0&&p<ota_MsgLists.size()){
            SendMessage sendMessage=ota_MsgLists.get(p);
            //Caused by: java.lang.IndexOutOfBoundsException: Index: 4880, Size: 2052
            sendLog2("--------------------\n");
            sendLog2("--EbelterScaleOtaUpdate--发送升级包--"+BytesUtils.bytes2HexStr(sendMessage.datas)+"--desc = "+sendMessage.desc);
            LogUtils.i(TAG,"--EbelterScaleOtaUpdate--发送升级包--"+BytesUtils.bytes2HexStr(sendMessage.datas)+"--desc = "+sendMessage.desc);
            if (mIOTA!=null)mIOTA.sendMsg2Scale(sendMessage,sendMessage.desc);
        }

    }



    //处理体脂秤的应答
    public void dealScaleResponse(int cmd, final int position){
        LogUtils.i(TAG,"--EbelterScaleOtaUpdate--cmd = " + cmd);
        if (cmd==0){//可以升级
            LogUtils.i(TAG,"--EbelterScaleOtaUpdate--收到可以ota升级的指令");
            sendLog2("--EbelterScaleOtaUpdate--收到可以ota升级的指令");
            otabytes2List();
        }else if (cmd==1){//数据包序号出错3次，退出升级
            LogUtils.i(TAG,"--EbelterScaleOtaUpdate--数据包序号出错3次，退出升级 position = "+position);
            sendLog2("--EbelterScaleOtaUpdate--数据包序号出错3次，退出升级 position = "+position);


            removeMessages(what_sendOtaPosition);
            otaPosition = position-1;
            //sendOtaList2Scale(otaPosition);

            CommonEventBus commonEventBus=new CommonEventBus(TAG,"CeshiActivity",23,"更新otaPosition");
            EventBus.getDefault().post(commonEventBus);



        }else if (cmd==2){//CS码出错，退出升级
            LogUtils.i(TAG,"--EbelterScaleOtaUpdate--CS码出错，退出升级");
            sendLog2("--EbelterScaleOtaUpdate--CS码出错，退出升级");
        }else if (cmd==3){//升级完成
            LogUtils.i(TAG,"--EbelterScaleOtaUpdate--升级完成");
            sendLog2("--EbelterScaleOtaUpdate--升级完成");
        }else if (cmd==5){
            LogUtils.i(TAG,"--EbelterScaleOtaUpdate--数据包 position="+position+"接收成功");


            postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendOtaList2Scale(position);
                }
            },0);

        }
    }



    private void sendLog2(String msg){
        CommonEventBus eventBus=new CommonEventBus(TAG,"CeshiActivity",22,msg);
        EventBus.getDefault().post(eventBus);
    }


    //把otabytes装成一个m
    private void otabytes2List() {




        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {
                ota_MsgLists=new ArrayList<>();
                int length = ota_ByteLists.length/8;
                int mod = ota_ByteLists.length%8;
                if (mod>0){
                    length=length+1;
                }
                ota_MsgLists.clear();
                for (int i=0;i<length;i++){
                    SendMessage m = new SendMessage();
                    m.desc="ota升级包i = "+(i+1)+"/"+length;
                    byte[] position = BytesUtils.getHLint(i+1);
                    byte[] cmdBytes=new byte[]{(byte) 0xab,0x0c, (byte) 0x94,position[1],position[0],
                            (byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,
                            (byte) 0xff};

                    if (i!=length-1){
                        System.arraycopy(ota_ByteLists,i*8,cmdBytes,5,8);
                    }else {
                        int chazhi = ota_ByteLists.length-i*8;
                        System.arraycopy(ota_ByteLists,i*8,cmdBytes,5,chazhi);
                    }
                    m.datas=cmdBytes;
                    m.isNeedEncrypt=false;
                    ota_MsgLists.add(m);
                }
                sendEmptyMessage(what_init_MsgLists_finish);

            }
        });

    }


    private IOTA mIOTA;
    public void setmIOTA(IOTA mIOTA) {
        this.mIOTA = mIOTA;
    }



    public interface IOTA{
        void sendMsg2Scale(SendMessage msg,String desc);
        void sendMsgs2Scale(List<SendMessage> msgs,String desc);

    }
}
